//
//  ProfileImageProcesser.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-3-26.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "ProfileImageProcesser.h"
#import "DataManager.h"
#import "PImage.h"
#import "TwitterClient.h"

static ProfileImageProcesser *outInstance;

@implementation ProfileImageProcesser

@synthesize delegate = _delegate;

@synthesize deflogo;

+ (ProfileImageProcesser *)getInstance{
	if(outInstance == nil){
		outInstance = [[ProfileImageProcesser alloc] init];
	}
	return outInstance;
}

- (id)init{
	if(self = [super init]){
		imageCache = [[NSMutableDictionary alloc] init];
		loading = NO;
		queue = [[NSMutableArray alloc] init];
		NSBundle *mainBundle = [NSBundle mainBundle];
		NSString *logoPath = [mainBundle pathForResource:@"twitterdeflogo" ofType:@"png"];
		UIImage *img = [[UIImage alloc] initWithContentsOfFile:logoPath];
		self.deflogo = img;
		[img release];
	}
	return self;
}

- (void)putImage:(NSString *)url withImage:(UIImage *)img{
	if(url && img){
		PImage *pimg = [[PImage alloc] init];
		pimg.imgData = img;
		[imageCache setObject:pimg forKey:url];
		[pimg release];
	}
}

- (UIImage *)getImage:(NSString *)url{
	UIImage *ret = nil;
	if(url){
		PImage *pimg = (PImage *)[imageCache objectForKey:url];
		ret = pimg.imgData;
	}
	return ret;
}

- (BOOL)haveImage:(NSString *)url{
	BOOL ret = NO;
	if(url){
		ret = [imageCache objectForKey:url] != nil;
	}
	return ret;
}

- (void)removeImage:(NSString *)url{
	if(url){
		PImage *pimg = (PImage *)[imageCache objectForKey:url];
		pimg.refCount = pimg.refCount - 1;
		if(pimg.refCount < 0){
			[imageCache removeObjectForKey:url];
		}
	}
}

- (void)loadImage:(NSString *)url{
	// TODO 加载图像，并且保存在cache中，并且进行通知
	if(url){
		if(![queue containsObject:url]){
			[queue addObject:url];
		}else{
			PImage *pimg = (PImage *)[imageCache objectForKey:url];
			if(pimg){
				pimg.refCount = pimg.refCount + 1;
			}
		}
	}
	if(!loading){
		loading = YES;
		[NSThread detachNewThreadSelector:@selector(loadThreadImpl) toTarget:self withObject:nil];
	}
}

- (void)loadImagesFromData{
	id obj = [DataManager loadObjectFromFile:@"pimgs.dat"];
	if(obj){
		if([obj isKindOfClass:[NSDictionary class]]){
			[imageCache addEntriesFromDictionary:((NSDictionary *)obj)];
		}
	}
}

- (void)saveImagesToData{
	[DataManager saveObjectToFile:imageCache withName:@"pimgs.dat"];
}

- (void)loadThreadImpl{
	NSInteger len;
	[[TwitterClient getInstance] setNetRef:1];
	while (true) {
		len = [queue count];
		if(len == 0){
			break;
		}
		NSString *url;
		NSURL *u;
		NSURLRequest *req;
		NSData *dt;
		NSError *err;
		NSHTTPURLResponse *resp;
		UIImage *img;
		for (int i = 0; i < len; i++) {
			url = (NSString *)[queue objectAtIndex:0];
			if(url){
				u = [[NSURL alloc] initWithString:url];
				req = [[NSURLRequest alloc] initWithURL:u];
				dt = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:&err];
				if(dt == nil && err != nil){
					[err release];
				}else{
					if(dt){
						img = [[UIImage alloc] initWithData:dt];
						PImage *pimg = [[PImage alloc] init];
						pimg.imgData = img;
						pimg.refCount = 1;
						[img release];
						[imageCache setObject:pimg forKey:url];
						[pimg release];
					}
				}
				[u release];
				[req release];
			}
			[queue removeObjectAtIndex:0];
		}
	}
	[[TwitterClient getInstance] setNetRef:0];
	loading = NO;
	if(_delegate){
		[_delegate imageDidLoadFinished:nil];
	}
}

- (void)dealloc{
	[imageCache release];
	[queue release];
	[super dealloc];
}

@end
